// app/service/cross_organization_analysis_service.js
'use strict';

const { Service } = require('egg');

class CrossOrganizationAnalysisService extends Service {
  // 获取跨组织客户分析数据
  async getCrossOrganizationCustomerAnalysis() {
    const { ctx } = this;
    
    try {
      // 获取用户所属的所有组织
      const userOrganizations = ctx.state.userOrganizations || [];
      const organizationIds = userOrganizations.map(org => org.id);
      
      if (organizationIds.length === 0) {
        return {
          organizations: [],
          summary: {
            totalCustomers: 0,
            totalOrders: 0,
            totalRevenue: 0
          },
          charts: {
            customerDistribution: [],
            revenueTrend: []
          }
        };
      }
      
      // 获取各组织的客户统计数据
      const organizationStats = await Promise.all(organizationIds.map(async (orgId) => {
        const org = userOrganizations.find(o => o.id === orgId);
        
        // 获取该组织的客户数量
        const customerCount = await ctx.model.CustomerModel.count({
          where: { organizationId: orgId }
        });
        
        // 获取该组织的订单数量和总金额
        const orders = await ctx.model.SalesOrderModel.findAll({
          where: { organizationId: orgId },
          attributes: [
            [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
            [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('amount')), 'totalAmount']
          ]
        });
        
        const orderCount = orders.length > 0 ? parseInt(orders[0].getDataValue('orderCount')) : 0;
        const totalAmount = orders.length > 0 ? parseFloat(orders[0].getDataValue('totalAmount')) || 0 : 0;
        
        return {
          id: orgId,
          name: org.name,
          customerCount,
          orderCount,
          totalAmount
        };
      }));
      
      // 计算汇总数据
      const summary = {
        totalCustomers: organizationStats.reduce((sum, org) => sum + org.customerCount, 0),
        totalOrders: organizationStats.reduce((sum, org) => sum + org.orderCount, 0),
        totalRevenue: organizationStats.reduce((sum, org) => sum + org.totalAmount, 0)
      };
      
      // 准备图表数据
      const customerDistribution = organizationStats.map(org => ({
        name: org.name,
        value: org.customerCount
      }));
      
      const revenueTrend = organizationStats.map(org => ({
        name: org.name,
        value: org.totalAmount
      }));
      
      return {
        organizations: organizationStats,
        summary,
        charts: {
          customerDistribution,
          revenueTrend
        }
      };
    } catch (error) {
      ctx.logger.error('获取跨组织客户分析数据失败:', error);
      throw error;
    }
  }
  
  // 获取跨组织销售分析数据
  async getCrossOrganizationSalesAnalysis() {
    const { ctx } = this;
    
    try {
      // 获取用户所属的所有组织
      const userOrganizations = ctx.state.userOrganizations || [];
      const organizationIds = userOrganizations.map(org => org.id);
      
      if (organizationIds.length === 0) {
        return {
          organizations: [],
          summary: {
            totalOrders: 0,
            totalRevenue: 0,
            avgOrderValue: 0
          },
          charts: {
            salesTrend: [],
            topProducts: []
          }
        };
      }
      
      // 获取各组织的销售统计数据
      const organizationStats = await Promise.all(organizationIds.map(async (orgId) => {
        const org = userOrganizations.find(o => o.id === orgId);
        
        // 获取该组织的订单数量和总金额
        const orders = await ctx.model.SalesOrderModel.findAll({
          where: { organizationId: orgId },
          attributes: [
            [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
            [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('order_amount')), 'totalAmount'],
            [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('order_amount')), 'avgAmount']
          ]
        });
        
        const orderCount = orders.length > 0 ? parseInt(orders[0].getDataValue('orderCount')) : 0;
        const totalAmount = orders.length > 0 ? parseFloat(orders[0].getDataValue('totalAmount')) || 0 : 0;
        const avgAmount = orders.length > 0 ? parseFloat(orders[0].getDataValue('avgAmount')) || 0 : 0;
        
        return {
          id: orgId,
          name: org.name,
          orderCount,
          totalAmount,
          avgAmount
        };
      }));
      
      // 计算汇总数据
      const totalOrders = organizationStats.reduce((sum, org) => sum + org.orderCount, 0);
      const totalRevenue = organizationStats.reduce((sum, org) => sum + org.totalAmount, 0);
      const avgOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;
      
      const summary = {
        totalOrders,
        totalRevenue,
        avgOrderValue
      };
      
      // 准备图表数据
      const salesTrend = organizationStats.map(org => ({
        name: org.name,
        value: org.totalAmount
      }));
      
      // 获取热门产品（跨所有组织）
      const topProducts = await ctx.model.ProductModel.findAll({
        where: {
          organizationId: organizationIds
        },
        attributes: [
          'name',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'productCount']
        ],
        group: ['name'],
        order: [[ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'DESC']],
        limit: 10
      });
      
      const topProductsData = topProducts.map(product => ({
        name: product.name,
        value: parseInt(product.getDataValue('productCount'))
      }));
      
      return {
        organizations: organizationStats,
        summary,
        charts: {
          salesTrend,
          topProducts: topProductsData
        }
      };
    } catch (error) {
      ctx.logger.error('获取跨组织销售分析数据失败:', error);
      throw error;
    }
  }
  
  // 获取跨组织财务分析数据
  async getCrossOrganizationFinancialAnalysis() {
    const { ctx } = this;
    
    try {
      // 获取用户所属的所有组织
      const userOrganizations = ctx.state.userOrganizations || [];
      const organizationIds = userOrganizations.map(org => org.id);
      
      if (organizationIds.length === 0) {
        return {
          organizations: [],
          summary: {
            totalRevenue: 0,
            totalExpenses: 0,
            netProfit: 0
          },
          charts: {
            financialTrend: [],
            expenseDistribution: []
          }
        };
      }
      
      // 获取各组织的财务统计数据
      const organizationStats = await Promise.all(organizationIds.map(async (orgId) => {
        const org = userOrganizations.find(o => o.id === orgId);
        
        // 获取该组织的总收入
        const revenueOrders = await ctx.model.SalesOrderModel.findAll({
          where: { organizationId: orgId },
          attributes: [
            [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('amount')), 'totalRevenue']
          ]
        });
        
        const totalRevenue = revenueOrders.length > 0 ? 
          parseFloat(revenueOrders[0].getDataValue('totalRevenue')) || 0 : 0;
        
        // 获取该组织的总支出（这里简化处理，实际应该关联采购等数据）
        // 暂时使用一个固定比例计算支出
        const totalExpenses = totalRevenue * 0.7; // 假设支出占收入的70%
        
        const netProfit = totalRevenue - totalExpenses;
        
        return {
          id: orgId,
          name: org.name,
          totalRevenue,
          totalExpenses,
          netProfit
        };
      }));
      
      // 计算汇总数据
      const summary = {
        totalRevenue: organizationStats.reduce((sum, org) => sum + org.totalRevenue, 0),
        totalExpenses: organizationStats.reduce((sum, org) => sum + org.totalExpenses, 0),
        netProfit: organizationStats.reduce((sum, org) => sum + org.netProfit, 0)
      };
      
      // 准备图表数据
      const financialTrend = organizationStats.map(org => ({
        name: org.name,
        revenue: org.totalRevenue,
        expenses: org.totalExpenses,
        profit: org.netProfit
      }));
      
      const expenseDistribution = organizationStats.map(org => ({
        name: org.name,
        value: org.totalExpenses
      }));
      
      return {
        organizations: organizationStats,
        summary,
        charts: {
          financialTrend,
          expenseDistribution
        }
      };
    } catch (error) {
      ctx.logger.error('获取跨组织财务分析数据失败:', error);
      throw error;
    }
  }
  
  // 获取跨组织供应商分析数据
  async getCrossOrganizationSupplierAnalysis() {
    const { ctx } = this;
    
    try {
      // 获取用户所属的所有组织
      const userOrganizations = ctx.state.userOrganizations || [];
      const organizationIds = userOrganizations.map(org => org.id);
      
      if (organizationIds.length === 0) {
        return {
          organizations: [],
          summary: {
            totalSuppliers: 0,
            activeSuppliers: 0,
            pendingSuppliers: 0
          },
          charts: {
            supplierDistribution: [],
            supplierStatus: []
          }
        };
      }
      
      // 使用视图查询各组织的供应商统计数据
      const organizationStats = await ctx.model.query(
        `SELECT 
          o.id,
          o.name,
          COALESCE(v.total_suppliers, 0) as totalSuppliers,
          COALESCE(v.active_suppliers, 0) as active,
          COALESCE(v.pending_suppliers, 0) as pending,
          COALESCE(v.suspended_suppliers, 0) as suspended,
          COALESCE(v.terminated_suppliers, 0) as terminated
        FROM organizations o
        LEFT JOIN v_multi_org_supplier_stats v ON o.id = v.organization_id
        WHERE o.id IN (?)`,
        {
          replacements: [organizationIds],
          type: ctx.app.Sequelize.QueryTypes.SELECT
        }
      );
      
      // 计算汇总数据
      const summary = {
        totalSuppliers: organizationStats.reduce((sum, org) => sum + parseInt(org.totalSuppliers), 0),
        activeSuppliers: organizationStats.reduce((sum, org) => sum + parseInt(org.active), 0),
        pendingSuppliers: organizationStats.reduce((sum, org) => sum + parseInt(org.pending), 0),
        suspendedSuppliers: organizationStats.reduce((sum, org) => sum + parseInt(org.suspended), 0),
        terminatedSuppliers: organizationStats.reduce((sum, org) => sum + parseInt(org.terminated), 0)
      };
      
      // 准备图表数据
      const supplierDistribution = organizationStats.map(org => ({
        name: org.name,
        value: parseInt(org.totalSuppliers)
      }));
      
      const supplierStatus = organizationStats.map(org => ({
        name: org.name,
        active: parseInt(org.active),
        pending: parseInt(org.pending),
        suspended: parseInt(org.suspended),
        terminated: parseInt(org.terminated)
      }));
      
      return {
        organizations: organizationStats,
        summary,
        charts: {
          supplierDistribution,
          supplierStatus
        }
      };
    } catch (error) {
      ctx.logger.error('获取跨组织供应商分析数据失败:', error);
      throw error;
    }
  }
}

module.exports = CrossOrganizationAnalysisService;